<template>
  <a-form :label-col="{span: 6}" :wrapper-col="{span: 16}">
    <a-form-item label="角色名称" v-bind="validateInfos.name">
      <a-input v-model:value="modelRef.name" v-focus/>
    </a-form-item>
    <a-form-item label="角色编码" v-bind="validateInfos.code">
      <a-input v-model:value="modelRef.code" />
    </a-form-item>

    <a-form-item :wrapper-col="{ span: 14, offset: 6 }">
      <a-space>
        <a-button @click="resetFields">重置</a-button>
        <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
      </a-space>
    </a-form-item>
  </a-form>
</template>
<script>
import { insert, update } from "@/api/sysRoleApi.ts";
import { defineComponent, reactive, toRaw } from "vue";
import { Form, message } from "ant-design-vue";
const useForm = Form.useForm;
export default defineComponent({
  props: {
    type: String,
    row: Object
  },
  setup(props, context) {
    const { type, row } = props;
    const modelRef = reactive({
      name: row?.name,
      code: row?.code
    });
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: "角色名称必填项"
        }
      ],
      code: [
        {
          required: true,
          message: "角色编码必填项"
        }
      ]
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const onSubmit = () => {
      validate()
        .then(() => {
          if (type == "insert") {
            insertData();
          } else if (type == "update") {
            updateData()
          }
        })
        .catch(err => {
          console.log("error", err);
        });
    };

    const insertData = () => {
      let form = toRaw(modelRef);
      insert(form).then(resd => {
        message.success("创建成功");
        context.emit("success", resd);
      });
    };

    const updateData = () => {
      let form = toRaw(modelRef);
      form.id = row.id
      update(form).then(resd => {
        message.success("更新成功");
        context.emit("success", resd);
      });
    };

    return {
      validateInfos,
      resetFields,
      modelRef,
      onSubmit
    };
  }
});
</script>